package com.tongguan.paypos.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.tongguan.paypos.R;
import com.tongguan.paypos.activity.trans.ResultManageActivity;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.PayInfo;
import com.tongguan.paypos.entity.ResponseInfo;
import com.tongguan.paypos.entity.RevokeInfo;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.utils.CipherUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;
import com.tongguan.paypos.view.CustomAlertDialog;
import com.tongguan.paypos.view.CustomInputDialog;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Joylive on 2016/12/14 .
 */

public class RevokeTransFragment extends BaseFragment {
    private static final int DELAYED_TIME = 5000;//
    private static final int REQUEST_CODE_COUPON = 10050;
    @BindView(R.id.btn_scan_bar)
    Button mBtnScanBar;
    @BindView(R.id.et_input_number)
    EditText mEtInputNumber;
    @BindView(R.id.btn_cancel_online)
    Button mBtnCancelOnline;

    private String orderId;
    private int count = 3;//查询次数

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_revoke_trans, container, false);
        ButterKnife.bind(this, rootView);
        setTitle("线上撤销");
        initPwd();
        initEvent();
        return rootView;
    }

    private void initEvent() {
        Intent intent = new Intent(frmCtx, CaptureActivity.class);
        Bundle b = new Bundle();
        b.putInt("cameraType", (int) SPUtils.getSp(frmCtx, AppConstants.CAMERA_TYPE, 0));
        intent.putExtras(b);
        mBtnScanBar.setOnClickListener(v ->
                startActivityForResult(intent, REQUEST_CODE_COUPON));
        mBtnCancelOnline.setOnClickListener(v -> {
            orderId = mEtInputNumber.getText().toString();
            if (TextUtils.isEmpty(orderId)) {
                ToastUtils.showCustom(frmCtx, "订单号不能为空");
                return;
            }
            revoke(orderId);
        });
    }

    private void initPwd() {
        new CustomInputDialog.Builder(frmCtx).setTitle("输入撤销密码")
                .setPositiveButton(R.string.common_sure, this::revokePwd)
               .setNegativeButton(R.string.common_cancel, (dialog, which) -> onBack()).show();
    }

    private void revokePwd(String pwd) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_REVOKE_PASSWORD, CipherUtils.md5(pwd));
        RequestCallback.post(frmCtx, UrlConstants.SUPERVISOR_PASSWORD, params, mDialog, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                ResponseInfo responseInfo = ResponseInfo.objectFromData(response);
                if (responseInfo.getStatus() != 100) {
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage(responseInfo.getMessage())
                            .setPositiveButton("重新输入", (dialog, which) -> initPwd())
                            .setNegativeButton(R.string.common_cancel, (dialog, which) -> onBack()).show();
                    return;
                }
                ToastUtils.showCustom(frmCtx, "输入订单号");
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> revokePwd(pwd))
                        .setNegativeButton(R.string.common_cancel, (dialog, which) -> onBack()).show();
            }
        });
    }

    private void revoke(String orderId) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_REVOKE_ORDER_ID, orderId);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(frmCtx, UrlConstants.BACKOUT_PAY, params, mDialog, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                RevokeInfo revokeInfo = RevokeInfo.objectFromData(response);
                if (revokeInfo.getStatus() != 100) {
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage(revokeInfo.getMessage())
                            .setPositiveButton(R.string.common_sure, null).show();
                    return;
                }
                if (!"2".equals(revokeInfo.getState())&&!"5".equals(revokeInfo.getState())) {
                    ToastUtils.showCustom(frmCtx, "撤销状态错误 " + revokeInfo.getStatus());
                    return;
                }
                if(revokeInfo.getChannelId().equals("YLSM")){
                    queryOder("");
                    return;
                }
                queryOderDetail();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> revoke(orderId))
                        .setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }

    /**
     * 查询上游订单接口
     *
     * @param msg 状态
     */
    private void queryOder(String msg) {
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
            mDialog.setLoadingMessage(msg + "\n正在查询，请稍等...");
        }
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(frmCtx, UrlConstants.QUERY_ORDER, params, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    //查询状态还是失败 继续查询
                    if (AppConstants.messageFilter(message)) { // 问题拦截
                        new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> {})
                                .show();
                        return;
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                if (!"2".equals(payInfo.getState())) {
                    //查询上游 订单
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                //成功跳转
                successJumpAct(transInfo);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mHandler.sendMessageDelayed(mHandler.obtainMessage(0, "查询订单网络异常"), DELAYED_TIME);
            }
        });
    }

    /**
     * 查询订单详情接口
     */
    private void queryOderDetail() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(frmCtx, UrlConstants.ORDER_DETAILS + orderId, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    ToastUtils.showCustom(frmCtx, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage(payInfo.getMessage() + "\n订单详情查询失败，是否重新请求")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    return;
                }
                //成功跳转
                successJumpAct(transInfo);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> queryOderDetail())
                        .setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }
    private void successJumpAct(TransInfo transInfo){
        //成功跳转
        Bundle bundle = new Bundle();
        bundle.putString(ResultManageActivity.EXCHANGE_FRAGMENT_NAME, ResultOrderDetailFragment.class.getName());
        bundle.putParcelable(ResultOrderDetailFragment.ORDER_DATA, transInfo);
        jumpFrm2Act(ResultManageActivity.class, bundle, true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            //线上支付
            if (requestCode == REQUEST_CODE_COUPON) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtInputNumber.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
        }
    }

    //签名
    private String signKey(Map map){
        String key = (String) SPUtils.getSp(frmCtx, AppConstants.SIGNATURE, "");
        return CipherUtils.Signature(map,key);
    }


    //延时
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!frmCtx.isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        String message = (String) msg.obj;
                        if (count > 0) {
                            queryOder(message);
                            count--;
                        } else {
                            new CustomAlertDialog.Builder(frmCtx).setTitle("支付失败")
                                    .setMessage(message)
                                    .setPositiveButton("再次查询", (dialog, which) -> queryOder(message))
                                    .setNegativeButton("取消订单", (dialog, which) -> {}).show();
                        }
                        break;
                }
            }
        }
    };
}
